/*
 * Copyright 2009 Max Kugland
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.splink.deepsplink.deeplink {
	import com.asual.swfaddress.SWFAddress;
	import com.asual.swfaddress.SWFAddressEvent;

	import org.splink.deepsplink.config.ConfigData;
	import org.splink.deepsplink.config.PageData;
	import org.splink.deepsplink.page.params.PageParameterUtil;

	/**
	 * Default <code>IDeeplinkStrategy</code> implementation which delegates the 
	 * deeplinking task to SWFAddress (http://www.asual.com/swfaddress/)
	 * 
	 * @author Max Kugland
	 */
	final public class SwfAddressDeeplinkStrategy implements IDeeplinkStrategy {
		private var _callback : Function;
		private var _config : ConfigData;

		public function SwfAddressDeeplinkStrategy(config : ConfigData) {
			_config = config;
		}

		/**
		 * @inheritDoc
		 */
		public function start() : void {
			SWFAddress.addEventListener(SWFAddressEvent.CHANGE, onAddressChange);
		}

		/**
		 * @inheritDoc
		 */
		public function setCallback(callback : Function) : void {
			_callback = callback;
		}

		/**
		 * @inheritDoc
		 */
		public function gotoPage(pageId : String) : void {
			setValue("/" + pageId + "/");
		}

		private function setValue(pageId : String) : void {
			SWFAddress.setValue(pageId);
		}

		private function getTitle(id : String, pages : Array) : String {
			for each (var page : PageData in pages) {
				if(page.id == id) {
					return page.title;
				} else {
					var title : String = getTitle(id, page.pageDataArray);
					if(title != null) {
						return title;
					}
				}
			}
			return null;
		}
		
		private function onAddressChange(event : SWFAddressEvent) : void {
			setTitle(event.value);
			_callback();
		}

		private function setTitle(pageId : String) : void {
			var id : String = PageParameterUtil.extractId(pageId).replace(/\//g, "");
			var title : String = getTitle(id, _config.pageData.pageDataArray);
			if(title != null) {
				SWFAddress.setTitle(title);
			} 
		}

		/**
		 * @inheritDoc
		 */
		public function getCurrentAddress() : String {
			return SWFAddress.getValue().replace(/\//g, "");
		}
		
		/**
		 * @inheritDoc
		 */
		public function finalize() : void {
			SWFAddress.removeEventListener(SWFAddressEvent.CHANGE, onAddressChange);
		}
	}
}
